package com.ruixun.shopmanagement.service.impl;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ruixun.shopmanagement.dao.UserMapper;
import com.ruixun.shopmanagement.entity.User;
import com.ruixun.shopmanagement.service.inter.UserService;
import com.ruixun.shopmanagement.util.MD5_BySpring;
import com.ruixun.shopmanagement.util.MyUUID;
import com.ruixun.shopmanagement.util.inter.Mail_tool;
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	UserMapper userMapper;
	@Autowired
	Mail_tool mail_tool;
	@Override
	public int checkUserNameisExist(String uname) {
		// TODO Auto-generated method stub
		return userMapper.selectUserNameisExist(uname);
	}

	@Override
	public int checkUserEmailisExist(String email) {
		// TODO Auto-generated method stub
		return userMapper.selectUserEmailisExist(email);
	}
	//开启事务
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public boolean registerNewUser(User user) {
		boolean result=false;
		user.setPassword(MD5_BySpring.MD5(user.getPassword()));  //将密码加密一下
		   user.setCode(MyUUID.getUUID());
		   user.setUid(MyUUID.getUUID());
		   user.setState(0);
//		boolean FieldisNull=CheckEntity.checkObjFieldIsNull(user);   //检测对象中是否有null字段
//		if(FieldisNull) { //如果仍有字段为空则返回false
//			return false;
//		}
		try {
			
			result=userMapper.insertUser(user);
			if(result) {  //如果注册成功,则发送邮箱
				boolean sentResult=mail_tool.sentCodeToActive(user.getEmail(), user.getCode());
				System.out.println("发送"+user.getEmail()+":"+sentResult);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		} finally {
			
		}
		return result;
	}
	//开启事务
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public boolean activeUser(String code) {
		if(userMapper.selectUserCodeisExist(code)==1) {
			return userMapper.updateUserState(code);
		}else {
			return false;
		}
		
	}
	@Override
	public User login(String username,String password) {
		// TODO Auto-generated method stub
		password=MD5_BySpring.MD5(password);
		return userMapper.selectUserName_UserPassword(username, password);
	}

	@Override
	public boolean checkUserActived(String username) {
		if(userMapper.selectUserStateIs1(username)==1) {
			return true;
		}
		return false;
	}
	
}
